import 'package:flutter/material.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:get/get.dart';
import 'package:travel/model/homepage.dart';
import 'package:travel/model/tourism.dart';
import 'package:travel/routes/index.dart';
import 'package:travel/screen/flutter_screenutil.dart';
import 'package:travel/utils/colors.dart';
import 'package:travel/utils/radian.dart';
import 'package:travel/utils/styles.dart';
import 'package:travel/utils/tools.dart';

class Article extends StatefulWidget {
  const Article({super.key});

  @override
  State<Article> createState() => _ArticleState();
}

class _ArticleState extends State<Article> {
  List<HomepageArticleModel> pageList = [];

  bool isLoading = false;

  bool hasNext = true;

  int total = 20;

  ScrollController scrollController = ScrollController();

  @override
  void initState() {
    initData();
    scrollController.addListener(() {
      if (isLoading == false &&
          scrollController.position.pixels >= scrollController.position.maxScrollExtent) {
        setState(() {
          isLoading = true;
        });
        loadMoreData();
      }
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return scrollView(context);
  }

  @override
  void dispose() {
    scrollController.dispose();
    super.dispose();
  }

  void initData() {
    pageList.add(HomepageArticleModel(
        isTop: true,
        imgUrl:
            'https://img1.baidu.com/it/u=3237643364,3711617777&fm=253&fmt=auto&app=138&f=JPEG?w=751&h=500',
        previewCount: 10,
        describe: '和家人果断在北京续住3天的神仙小院',
        avatar:
            'https://img2.baidu.com/it/u=758153736,4149288328&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500',
        nickname: '晚风心里吹'));
    pageList.add(HomepageArticleModel(
        imgUrl:
            'https://img0.baidu.com/it/u=1532705034,533831030&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500',
        previewCount: 10,
        describe: '和家人果断在北京续住3天的神仙小院',
        avatar:
            'https://img2.baidu.com/it/u=758153736,4149288328&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500',
        nickname: '晚风心里吹'));
    pageList.add(HomepageArticleModel(
        imgUrl:
            'https://img0.baidu.com/it/u=1532705034,533831030&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500',
        previewCount: 10,
        describe: '和家人果断在北京续住3天的神仙小院',
        avatar:
            'https://img2.baidu.com/it/u=758153736,4149288328&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500',
        nickname: '晚风心里吹'));
    pageList.add(HomepageArticleModel(
        imgUrl:
            'https://img0.baidu.com/it/u=1532705034,533831030&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500',
        previewCount: 10,
        describe: '和家人果断在北京续住3天的神仙小院',
        avatar:
            'https://img2.baidu.com/it/u=758153736,4149288328&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500',
        nickname: '晚风心里吹'));
    pageList.add(HomepageArticleModel(
        imgUrl:
            'https://img0.baidu.com/it/u=1532705034,533831030&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500',
        previewCount: 10,
        describe: '和家人果断在北京续住3天的神仙小院',
        avatar:
            'https://img2.baidu.com/it/u=758153736,4149288328&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500',
        nickname: '晚风心里吹'));
    pageList.add(HomepageArticleModel(
        imgUrl:
            'https://img0.baidu.com/it/u=1532705034,533831030&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500',
        previewCount: 10,
        describe: '和家人果断在北京续住3天的神仙小院',
        avatar:
            'https://img2.baidu.com/it/u=758153736,4149288328&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500',
        nickname: '晚风心里吹'));
  }

  Widget scrollView(BuildContext context) {
    return CustomScrollView(
      controller: scrollController,
      slivers: [
        SliverOverlapInjector(handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context)),
        SliverPadding(
            padding: EdgeInsets.only(left: 10.w, right: 10.w, top: 10.h),
            sliver: SliverToBoxAdapter(
              child: StaggeredGrid.count(
                crossAxisCount: 2,
                crossAxisSpacing: 5.w,
                mainAxisSpacing: 10.h,
                children: pageList.map((row) {
                  double width = ToolsUtils.calculateTextHeight(
                      context, ' ${row.previewCount}', FontWeight.normal, 12.sp, 150.w, 1);
                  return InkWell(
                    onTap: () {
                      TourismModel model = TourismModel(
                          imgUrl: row.imgUrl,
                          describe: row.describe,
                          avatar: row.avatar,
                          browse: row.previewCount.toDouble(),
                          nickname: row.nickname);
                      Get.toNamed(RoutePath.attractionsArticle, arguments: {'model': model});
                    },
                    child: Container(
                      decoration: const BoxDecoration(color: Colors.white),
                      child: Column(
                        children: [
                          Container(
                            width: 172.w,
                            height: 215.h,
                            decoration: BoxDecoration(
                                borderRadius: BorderRadius.only(
                                    topLeft: Radius.circular(8.w), topRight: Radius.circular(8.w)),
                                image: DecorationImage(
                                    image: NetworkImage(row.imgUrl),
                                    fit: BoxFit.cover,
                                    alignment: Alignment.topLeft)),
                            child: Stack(
                              fit: StackFit.expand,
                              children: [
                                if (row.isTop)
                                  Positioned(
                                      top: 0,
                                      left: 0,
                                      child: SizedBox(
                                        width: 48.w,
                                        height: 45.h,
                                        child: CustomPaint(
                                          painter: _MyCustomPaint(),
                                          child: Transform.rotate(
                                            angle: RadianUtils.angleToRadian(318),
                                            child: Container(
                                              padding: const EdgeInsets.only(top: 5),
                                              alignment: Alignment.topCenter,
                                              child: Text(
                                                '置顶',
                                                style: StylesUtils.customTextStyle(
                                                    fontSize: 13.sp,
                                                    color: ColorsUtils.colorFfff,
                                                    fontWeight: FontWeight.bold),
                                              ),
                                            ),
                                          ),
                                        ),
                                      )),
                                Positioned(
                                    left: 5.w,
                                    bottom: 5.w,
                                    child: Container(
                                      constraints:
                                          BoxConstraints(minHeight: 18.h, maxWidth: width + 25.w),
                                      decoration: BoxDecoration(
                                          borderRadius: BorderRadius.circular(9.h),
                                          color: ColorsUtils.rgba(0, 0, 0, 0.698039215686274)),
                                      alignment: Alignment.center,
                                      child: Text.rich(TextSpan(children: [
                                        WidgetSpan(
                                            child: ToolsUtils.assetImageSvg('u2896.svg',
                                                width: 14.w, height: 9.h),
                                            alignment: PlaceholderAlignment.middle),
                                        TextSpan(
                                            text: ' ${row.previewCount}',
                                            style: StylesUtils.customTextStyle(
                                                color: ColorsUtils.colorF2f2, fontSize: 12.sp))
                                      ])),
                                    ))
                              ],
                            ),
                          ),
                          Container(
                            padding: EdgeInsets.symmetric(vertical: 10.h, horizontal: 5.h),
                            decoration: BoxDecoration(
                                color: Colors.white,
                                borderRadius: BorderRadius.only(
                                    bottomLeft: Radius.circular(8.w),
                                    bottomRight: Radius.circular(8.w))),
                            child: Column(
                              children: [
                                Container(
                                  alignment: Alignment.centerLeft,
                                  child: Text(
                                    row.describe,
                                    style: StylesUtils.customTextStyle(
                                        fontSize: 13.sp,
                                        fontWeight: FontWeight.w700,
                                        color: ColorsUtils.color3333,
                                        lineHeight: 1.5.h),
                                    maxLines: 2,
                                    overflow: TextOverflow.ellipsis,
                                  ),
                                ),
                                Container(
                                  margin: EdgeInsets.only(top: 10.h),
                                  alignment: Alignment.centerLeft,
                                  child: Row(
                                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                    children: [
                                      Text.rich(TextSpan(children: [
                                        WidgetSpan(
                                            child: CircleAvatar(
                                              radius: 10.w,
                                              backgroundImage: NetworkImage(row.avatar),
                                            ),
                                            alignment: PlaceholderAlignment.middle),
                                        TextSpan(
                                            text: ' ${row.nickname}',
                                            style: StylesUtils.customTextStyle(
                                                fontSize: 12.sp, color: ColorsUtils.color9999))
                                      ])),
                                      ToolsUtils.assetImageSvg('u2156.svg',
                                          width: 15.w, height: 4.h)
                                    ],
                                  ),
                                )
                              ],
                            ),
                          )
                        ],
                      ),
                    ),
                  );
                }).toList(),
              ),
            )),
        if (hasNext == false) noBottom() else if (isLoading == true) renderBottom()
      ],
    );
  }

  Future<void> loadMoreData() {
    return Future.delayed(const Duration(seconds: 1), () {
      setState(() {
        if (total > pageList.length) {
          hasNext = true;
          isLoading = false;
          onLoading();
          return;
        }
        hasNext = false;
        isLoading = false;
      });
    });
  }

  void onLoading() async {
    setState(() {
      /// 添加数据
      pageList.add(HomepageArticleModel(
          imgUrl:
              'https://img0.baidu.com/it/u=1532705034,533831030&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500',
          previewCount: 10,
          describe: '和家人果断在北京续住3天的神仙小院',
          avatar:
              'https://img2.baidu.com/it/u=758153736,4149288328&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500',
          nickname: '晚风心里吹'));
      pageList.add(HomepageArticleModel(
          imgUrl:
              'https://img0.baidu.com/it/u=1532705034,533831030&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500',
          previewCount: 10,
          describe: '和家人果断在北京续住3天的神仙小院',
          avatar:
              'https://img2.baidu.com/it/u=758153736,4149288328&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500',
          nickname: '晚风心里吹'));
    });
  }

  SliverToBoxAdapter noBottom() {
    return SliverToBoxAdapter(
      child: Container(
        padding: const EdgeInsets.symmetric(vertical: 15),
        alignment: Alignment.center,
        child: const Text(
          '已经到底',
          style: TextStyle(
            fontSize: 15,
            color: Color(0xFF333333),
          ),
        ),
      ),
    );
  }

  SliverToBoxAdapter renderBottom() {
    if (isLoading == true) {
      return SliverToBoxAdapter(
          child: Container(
        padding: const EdgeInsets.symmetric(vertical: 15),
        child: const Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              '努力加载中...',
              style: TextStyle(
                fontSize: 15,
                color: Color(0xFF333333),
              ),
            ),
            Padding(padding: EdgeInsets.only(left: 10)),
            SizedBox(
              width: 20,
              height: 20,
              child: CircularProgressIndicator(strokeWidth: 3),
            ),
          ],
        ),
      ));
    }
    return SliverToBoxAdapter(
        child: Container(
      padding: const EdgeInsets.symmetric(vertical: 15),
      alignment: Alignment.center,
      child: const Text(
        '上拉加载更多',
        style: TextStyle(
          fontSize: 15,
          color: Color(0xFF333333),
        ),
      ),
    ));
  }
}

class _MyCustomPaint extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    Paint paint = Paint()
      ..color = ColorsUtils.parseColorFromHexString(ColorsUtils.colorFfb8)
      ..isAntiAlias = true
      ..style = PaintingStyle.fill;
    Path path = Path();
    path.moveTo(0, 18);
    path.lineTo(0, size.height);
    path.lineTo(size.width, 0);
    path.lineTo(18, 0);
    path.close();
    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return this != oldDelegate;
  }
}
